#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库模型定义
使用SQLAlchemy ORM定义数据表结构
"""

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
try:
    # SQLAlchemy 1.4+
    from sqlalchemy import JSON
except ImportError:
    # SQLAlchemy 1.3 compatibility
    from sqlalchemy.dialects.mysql import JSON

db = SQLAlchemy()

class User(db.Model):
    """用户表"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), unique=True, nullable=False, index=True)
    password = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(100), nullable=True, index=True)
    role = db.Column(db.String(20), default='user', nullable=False)
    permissions = db.Column(db.JSON, default=lambda: ['read'])
    is_active = db.Column(db.Boolean, default=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': str(self.id),
            'username': self.username,
            'email': self.email,
            'role': self.role,
            'permissions': self.permissions,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<User {self.username}>'


class Project(db.Model):
    """项目表"""
    __tablename__ = 'projects'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, index=True)
    description = db.Column(db.Text, nullable=True)
    created_by = db.Column(db.String(50), nullable=False, index=True)
    status = db.Column(db.String(20), default='active', nullable=False, index=True)
    tags = db.Column(db.JSON, default=list)
    settings = db.Column(db.JSON, default=dict)
    created_at = db.Column(db.DateTime, default=datetime.now, nullable=False, index=True)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': str(self.id),
            'name': self.name,
            'description': self.description,
            'created_by': self.created_by,
            'status': self.status,
            'tags': self.tags,
            'settings': self.settings,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Project {self.name}>'


class Interface(db.Model):
    """接口表"""
    __tablename__ = 'interfaces'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, index=True)
    method = db.Column(db.String(10), nullable=False, index=True)  # GET, POST, PUT, DELETE
    url = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text, nullable=True)
    project_id = db.Column(db.Integer, nullable=True, index=True)
    status = db.Column(db.String(20), default='active', nullable=False, index=True)
    headers = db.Column(db.JSON, default=dict)
    parameters = db.Column(db.JSON, default=dict)
    response_schema = db.Column(db.JSON, default=dict)
    created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': str(self.id),
            'name': self.name,
            'method': self.method,
            'url': self.url,
            'description': self.description,
            'project_id': self.project_id,
            'status': self.status,
            'headers': self.headers,
            'parameters': self.parameters,
            'response_schema': self.response_schema,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Interface {self.method} {self.name}>'


class TestCase(db.Model):
    """测试案例表"""
    __tablename__ = 'test_cases'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, index=True)
    description = db.Column(db.Text, nullable=True)
    type = db.Column(db.String(50), nullable=False, index=True)  # UI自动化, 接口自动化, 性能测试等
    project_id = db.Column(db.Integer, nullable=True, index=True)
    interface_id = db.Column(db.Integer, nullable=True, index=True)
    status = db.Column(db.String(20), default='active', nullable=False, index=True)
    priority = db.Column(db.String(10), default='medium', nullable=False)  # high, medium, low
    test_data = db.Column(db.JSON, default=dict)
    expected_result = db.Column(db.Text, nullable=True)
    created_by = db.Column(db.String(50), nullable=False, index=True)
    created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': str(self.id),
            'name': self.name,
            'description': self.description,
            'type': self.type,
            'project_id': self.project_id,
            'interface_id': self.interface_id,
            'status': self.status,
            'priority': self.priority,
            'test_data': self.test_data,
            'expected_result': self.expected_result,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<TestCase {self.name}>'